<?php

class UsersController extends AppController {

    public $layout = "admin";
    
    public $sl_usuarios = array(
        "actions" => array("V" => "view", "E" => "edit", "D" => "delete"),
        "filters" => array(
            array("name" => 'User.name', "label" => 'Nombre'),
            array("name" => 'User.username', "label" => 'Usuario'),
            array("name" => 'Rol.id', "label" => 'Rol', "presentation" => "SELECT", "classparams" => '{"model":"Rol"}')
        ),
        "columns" => array(
            array("name" => 'User.name', "label" => 'Nombre'),
            array("name" => 'User.username', "label" => 'Usuario'),
            array("name" => 'Rol.nombre', "label" => 'Rol')
        )
    );
    public $maint_usuarios = array(
        "fields" => array(
            "Datos del Usuario" => array(
                array("name" => "name", "label" => "Nombre"),
                array("name" => "username", "label" => "Usuario"),
                array("name" => "password", "label" => "Clave", "presentation" => "PASSWORD", "actions" => "A|E", 'note' => 'Se mantiene la actual si se deja vacío.'),
                array("name" => "email", "label" => "Email"),
                array("name" => "rol_id", "label" => "Rol", "presentation" => "SELECT", "classparams" => '{"model":"Rol"}')
            )
        )
    );
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('login', 'logout');
    }

    public function add() {
        $this->maint = $this->maint_usuarios;
        parent::add();
    }

    public function edit($id = null) {
        if ($this->request->is('get')) {
            unset($this->request->data['User']['password']);
        }

        $this->maint = $this->maint_usuarios;
        parent::edit($id);
    }

    public function index() {
        $this->search_list = $this->sl_usuarios;
        parent::index();
    }

    public function view($id = null) {
        $this->maint = $this->maint_usuarios;
        parent::view($id);
    }

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Usuario y contraseña incorrectos'));
            }
        } else {
            if ($this->Auth->loggedIn()) {
                $this->redirect(array('plugin' => null, 'controller' => 'pages', 'action' => 'display')); # homepage
            }
        }
    }

    public function logout() {
        // Importantisimo destruir la session, sino quedan los permisos
        $this->Session->destroy();
        $this->redirect($this->Auth->logout());
    }

}